package com.ytjj.qmyx.admin.controller;

import com.aliyun.oss.OSSClient;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.FileResponse;
import com.ytjj.common.utils.AliyunOSSClientUtil;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.annotation.OperLog;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件操作
 */
@Slf4j
@RestController
@RequestMapping("/oss")
public class UploadController {

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @PostMapping("/upload")
    @OperLog(operModule = "文件操作模块", operDesc = "上传文件", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult getImgUrl(@RequestParam("file") MultipartFile file, @RequestParam(value = "type",required = false) String type) {
        if (file.isEmpty()) {
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_EXIST));
        }
        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 ===>" + file.getOriginalFilename());

        String folder = "" ;
        if(type == null ){
            type = "";
        }
        switch(type){
            case "images" :
                folder = "images";
                break;
            case "dynamic" :
                folder = "dynamic";
                break;
            default :
                folder = "other";
        }

        FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, folder);
        if (fileResponse == null) {
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_UPLOAD_ERROR));
        }
        return CommonResult.success(fileResponse);
    }

    @PostMapping("/uploadImgAndCompress")
    @OperLog(operModule = "文件操作模块", operDesc = "上传压缩图片", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult uploadImgAndCompress(@RequestParam("file") MultipartFile file, @RequestParam(value = "type",required = false) String type) {
        if (file.isEmpty()) {
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_EXIST));
        }
        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 ===>" + file.getOriginalFilename());
        FileResponse fileResponse = AliyunOSSClientUtil.uploadCompressImgToOSS(ossClient, file, "images");
        if (fileResponse == null) {
            return CommonResult.failed("上传失败！仅支持jpg/jpeg/png/webp格式的图片！");
        }
        return CommonResult.success(fileResponse);
    }

    @PostMapping("/moreUpload")
    @OperLog(operModule = "文件操作模块", operDesc = "上传文件", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult getImgUrl(@RequestParam("file") MultipartFile[] file, @RequestParam(value = "type",required = false) String type) {
        List<FileResponse> responseList = new ArrayList<>();
        for(MultipartFile multipart : file) {
            FileResponse fileResponse = new FileResponse();
            if (multipart.isEmpty()) {
                return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_EXIST));
            }
            // 初始化OssClient
            OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
            log.info("开始上传文件 ===>" + multipart.getOriginalFilename());

            String folder = "" ;
            if(type == null ){
                type = "";
            }
            switch(type){
                case "images" :
                    folder = "images";
                    break;
                case "dynamic" :
                    folder = "dynamic";
                    break;
                default :
                    folder = "other";
            }

            fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, multipart, folder);
            if (fileResponse == null) {
                return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_UPLOAD_ERROR));
            }
            responseList.add(fileResponse);
        }
        return CommonResult.success(responseList);
    }

    @PostMapping("/wmTextUpload")
    @OperLog(operModule = "文件操作模块", operDesc = "上传文件+文字水印", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult wmTextUpload(@RequestParam("file") MultipartFile file) {
        //文件不能为空
        if (file.isEmpty()) {
            return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_EXIST));
        }

        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 ===>" + file.getOriginalFilename());

        FileResponse fileResponse = null;
        String suffix = Objects.requireNonNull(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')));
        try(
                InputStream inputStream = file.getInputStream();
                ByteArrayOutputStream os = new ByteArrayOutputStream();)
        {
            //获取图片名称
            //String fileName = file.getOriginalFilename();
            //LocalDateTime now = LocalDateTime.now();
            Image srcImg = ImageIO.read(inputStream);
            //给图片加上水印
            Font font = new Font("微软雅黑", Font.PLAIN, 20);
            String waterMarkContent = "测试文字水印";
            Color color = new Color(255, 0, 0, 179);
            if (srcImg != null) {
                int srcImgWidth = srcImg.getWidth(null);
                int srcImgHeight = srcImg.getHeight(null);
                //增加水印操作
                BufferedImage bufferedImage = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = bufferedImage.createGraphics();
                g.drawImage(srcImg, 1, 2, srcImgWidth, srcImgHeight, null);
                //根据图片背景设置水印颜色
                g.setColor(color);
                g.setFont(font);
                g.drawString(waterMarkContent, 100, 100);
                g.dispose();
                ImageIO.write(bufferedImage, "jpg", os);
                bufferedImage.flush();
                try (InputStream input = new ByteArrayInputStream(os.toByteArray())){
                    fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, input, suffix);
                    if (fileResponse == null) {
                        return CommonResult.failed(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_UPLOAD_ERROR));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.success(fileResponse);
    }

    @PostMapping("/wmImgUpload")
    @OperLog(operModule = "文件操作模块", operDesc = "上传文件+图片水印", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult wmImgUpload(@RequestParam("file") MultipartFile file, @RequestParam("wmFile") MultipartFile wmFile) {
        //file-上传文件 wmFile-水印文件
        if (file == null || wmFile == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_EXIST));
        }

        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 =======> " + file.getOriginalFilename());

        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf('.'));
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            //上传文件操作
            InputStream inputStream01 = file.getInputStream();
            Image srcImg = ImageIO.read(inputStream01);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = buffImg.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
                    srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            //水印文件操作
            InputStream inputStream02 = wmFile.getInputStream();
            ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(inputStream02));
            Image logoImg = logoImgIcon.getImage();

            //旋转
            double degree = 1;
            if (degree > 0) {
                graphics.rotate(Math.toRadians(degree),
                        (double) buffImg.getWidth() / 2,
                        (double) buffImg.getWidth() / 2);
            }

            float alpha = 1f; // 透明度
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            //水印 的位置
            graphics.drawImage(logoImg, buffImg.getWidth() / 3, buffImg.getHeight() / 2, null);
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            graphics.dispose();

            // 生成图片
            ImageIO.write(buffImg, "jpg", os);

            InputStream input = new ByteArrayInputStream(os.toByteArray());
            FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, input, suffix);

            return CommonResult.success(fileResponse);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

}

